package plan

import (
	"fmt"
	"mini-sql/expression"
	"mini-sql/model"
	"mini-sql/storage"
)

type ScanPlanNode struct {
	selectStatement *model.SelectStatement
	storePool       *storage.StorePool
	tableStore      storage.StoreInterface
	tableIter       storage.StoreIterator
}

func NewScanPlanNode(selectStatement *model.SelectStatement, storePool *storage.StorePool) PlanNode {
	return &ScanPlanNode{
		storePool:       storePool,
		selectStatement: selectStatement,
	}
}

func (p *ScanPlanNode) Prepare() error {
	tableName, err := expression.GetTableName(p.selectStatement.FromClause)
	if err != nil {
		return err
	}
	if tableName == "" {
		return fmt.Errorf("SelectPlan: tableName is empty")
	}
	tableStore, err := p.storePool.GetTableStore(tableName)
	if err != nil {
		return err
	}
	p.tableStore = tableStore
	p.tableIter = tableStore.GetIterator()
	return nil
}

func (p *ScanPlanNode) GetNextTuple() (*model.TableTuple, error) {
	return p.tableIter.GetNextTuple()
}
